<template>
  <div>
    <el-dialog v-model="dialogVisible" style="width: 80vw; max-width: 80vw;">
      <div class="toolbar">
        <el-input :model-value="currentDirectory"></el-input>
        <IconButton :tooltip="'To parent directory'" @click="gotoParent_">
          <el-icon>
            <Top></Top>
          </el-icon>
        </IconButton>
        <IconButton :tooltip="'Select this directory'" v-if="selectMode == 'directory'" @click="select">
          <el-icon>
            <Select />
          </el-icon>
        </IconButton>
      </div>

      <div class="directory-list">
        <div v-for="(value, index) in fsItemsList" :key="index" @click="itemClicked(value)" class="fs-item">
          <el-icon>
            <Folder v-if="value.type == 'directory'" />
            <Document v-else />
          </el-icon>
          <a v-if="value.type == 'directory'" @click="gotoSubDir_(value.name)">{{ value.name }}</a>
          <a v-else>{{ value.name }}</a>
        </div>
      </div>
    </el-dialog>
    <el-button @click="dialogVisible = true">...</el-button>
  </div>
</template>
<script setup lang="ts">
import { Folder, Document, Top, Select } from "@element-plus/icons-vue";
import { ElDialog, ElButton, ElIcon, ElInput } from "element-plus"
import { IconButton } from "../base"
</script>

<script lang="ts">
import { defineComponent, PropType } from "vue";
import { jsonRequest } from "../../requests"
// import { getFSItems, gotoSubDir, gotoParentDir } from "@/api/fs";
import { FileSystemItem, FSResponseData } from "./fs-model"

const urlJoin = (base: string, ...parts: string[]): string => {
  // 使用 map 函数处理每个部分，移除前后的斜杠
  const cleanedParts = parts.map(part => part.replace(/^\/+|\/+$/g, ''));
  // 使用 join 函数将处理后的部分连接起来，并用单个斜杠分隔
  const fullPath = cleanedParts.join('/');
  // 返回完整的URL
  return base + '/' + fullPath;
};




export default defineComponent({
  emits: ["select-directory", "select-file"],
  props: {
    url: { type: String, required: true },
    selectMode: {
      type: String as PropType<"directory" | "file">,
      default: () => "directory"
    }
  },
  data() {
    return {
      dialogVisible: false,
      currentDirectory: "C:\\Users\\houzh",
      fsItemsList: [] as FileSystemItem[],
    };
  },
  mounted() {
    this.getFSItems_();
  },
  methods: {
    formatURL(relURL: string) {
      return urlJoin(this.url, relURL);
    },
    async gotoSubDir(directory: string, subdir: string): Promise<FSResponseData> {
      return (await jsonRequest.get(this.formatURL("go_to_sub_dir",), { params: { directory: directory, subdir: subdir } }));
    },
    async gotoParentDir(directory: string): Promise<FSResponseData> {
      return (await jsonRequest.get(this.formatURL("go_to_parent_dir"), { params: { directory: directory } }));
    },
    async getFSItems(directory: string): Promise<FSResponseData> {
      return (await jsonRequest.get(this.formatURL("get_fs_items"), { params: { directory: directory } }));
    },
    async onSelectDirectory() {
      let directory = await (window as any).showDirectoryPicker({
        startIn: "desktop",
      }); // 从桌面开始选择文件。
      for await (const entry of directory.values()) {
        console.log("directory selected!", entry);
      }
    },
    async getFSItems_() {
      const fsItems = await this.getFSItems(this.currentDirectory);
      this.currentDirectory = fsItems.currentDirectory;
      this.fsItemsList = fsItems.fsItemsList;
    },

    async gotoSubDir_(subdirName: string) {
      const fsItems = await this.gotoSubDir(this.currentDirectory, subdirName);
      this.currentDirectory = fsItems.currentDirectory;
      this.fsItemsList = fsItems.fsItemsList;
    },

    async gotoParent_() {
      const fsItems = await this.gotoParentDir(this.currentDirectory);
      this.currentDirectory = fsItems.currentDirectory;
      this.fsItemsList = fsItems.fsItemsList;
    },

    itemClicked(item: FileSystemItem) {
      if ((this.selectMode == "file") && (item.type == "file")) {
        this.$emit("select-file", item.absPath)
        this.dialogVisible = false;
        return
      }
    },

    select() {
      this.$emit("select-directory", this.currentDirectory);
      this.dialogVisible = false;
    },
  },
});
</script>

<style scoped>
.toolbar {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.directory-list {
  max-height: 60vh;
  width: 100%;
  overflow: scroll;
  margin-top: 12px;
}

.directory-list .fs-item {
  text-align: left;
  text-wrap-mode: nowrap;
}

.directory-list .fs-item a {
  cursor: pointer;
}
</style>